/**
 * 用户消息管理模块
 * 支持国际化的新架构
 */
const {
	messageCollection,
	dbCmd
} = require('../../common/constants')
const {
	ERROR
} = require('../../common/error')
const {
	transformMultiLangData
} = require('../../lib/transform')
const {
	getUserId
} = require('../../common/utils')

module.exports = {
	/**
	 * 获取用户消息列表
	 * @param {object} params 查询参数
	 * @param {string} [params.type] 消息类型
	 * @param {number} [params.page=1] 页码
	 * @param {number} [params.limit=20] 每页数量
	 * @returns {object} 消息列表
	 */
	async getMessageList(params = {}) {
		const { type, page = 1, limit = 20 } = params
		
		try {
			const userId = await getUserId(this)
			
			// 构建查询条件
			let whereCondition = {
				user_id: userId
			}
			
			if (type) {
				whereCondition.type = type
			}
			
			// 分页查询
			const skip = (page - 1) * limit
			const messageResult = await messageCollection
				.where(whereCondition)
				.orderBy('create_time', 'desc')
				.skip(skip)
				.limit(limit)
				.get()
			
			// 获取总数和未读数量
			const [countResult, unreadResult] = await Promise.all([
				messageCollection.where(whereCondition).count(),
				messageCollection.where({
					user_id: userId,
					is_read: false
				}).count()
			])
			
			// 获取当前请求的语言
			const language = this.language || 'zh-Hans'
			
			// 转换数据格式
			const transformedData = transformMultiLangData(messageResult.data, language, {
				multiLangFields: ['title', 'content'],
				keepFields: [
					'message_id', 'user_id', 'type', 'is_read', 'priority',
					'data', 'read_time', 'create_time', 'update_time'
				],
				idMapping: { '_id': 'message_id' }
			})
			
			// 为 device_share 类型的消息附加分享状态
			const db = uniCloud.database()
			const shareCollection = db.collection('sh_user_share')
			
			for (let message of transformedData) {
				if (message.type === 'device_share' && message.data && message.data.share_id) {
					try {
						const shareResult = await shareCollection.doc(message.data.share_id).get()
						if (shareResult.data.length > 0) {
							const share = shareResult.data[0]
							// 将分享状态添加到消息数据中
							message.data.share_status = share.status
							message.data.accept_time = share.accept_time
							message.data.reject_reason = share.reject_reason
						}
					} catch (error) {
						console.error('查询分享状态失败:', error)
					}
				}
			}
			
			return {
				list: transformedData,
				total: countResult.total,
				unreadCount: unreadResult.total,
				page,
				limit,
				totalPages: Math.ceil(countResult.total / limit)
			}
		} catch (error) {
			console.error('getMessageList error:', error)
			throw error
		}
	},
	
	/**
	 * 标记消息为已读
	 * @param {object} params 标记参数
	 * @param {string} params.messageId 消息ID
	 * @returns {object} 标记结果
	 */
	async markAsRead(params) {
		const { messageId } = params
		
		if (!messageId) {
			throw {
				errCode: ERROR.PARAM_REQUIRED,
				errMsgValue: { param: 'messageId' }
			}
		}
		
		try {
			const userId = await getUserId(this)
			
			// 检查消息权限并更新
			const updateResult = await messageCollection.where({
				_id: messageId,
				user_id: userId
			}).update({
				is_read: true,
				read_time: new Date(),
				update_time: new Date()
			})
			
			if (updateResult.updated === 0) {
				throw {
					errCode: ERROR.MESSAGE_NOT_FOUND
				}
			}
			
			return {
				success: true,
				message: this.t('message.mark_read_success')
			}
		} catch (error) {
			console.error('markAsRead error:', error)
			throw error
		}
	},
	
	/**
	 * 批量标记消息为已读
	 * @param {object} params 批量标记参数
	 * @param {Array} params.messageIds 消息ID列表
	 * @returns {object} 标记结果
	 */
	async batchMarkAsRead(params) {
		const { messageIds } = params
		
		if (!messageIds || !Array.isArray(messageIds) || messageIds.length === 0) {
			throw {
				errCode: ERROR.PARAM_REQUIRED,
				errMsgValue: { param: 'messageIds' }
			}
		}
		
		try {
			const userId = await getUserId(this)
			
			// 批量更新
			const updateResult = await messageCollection.where({
				_id: dbCmd.in(messageIds),
				user_id: userId
			}).update({
				is_read: true,
				read_time: new Date(),
				update_time: new Date()
			})
			
			return {
				success: true,
				message: this.t('message.batch_mark_read_success'),
				updated: updateResult.updated
			}
		} catch (error) {
			console.error('batchMarkAsRead error:', error)
			throw error
		}
	},
	
	/**
	 * 删除消息
	 * @param {object} params 删除参数
	 * @param {string} params.messageId 消息ID
	 * @returns {object} 删除结果
	 */
	async deleteMessage(params) {
		const { messageId } = params
		
		if (!messageId) {
			throw {
				errCode: ERROR.PARAM_REQUIRED,
				errMsgValue: { param: 'messageId' }
			}
		}
		
		try {
			const userId = await getUserId(this)
			
			// 检查消息权限并删除
			const deleteResult = await messageCollection.where({
				_id: messageId,
				user_id: userId
			}).remove()
			
			if (deleteResult.deleted === 0) {
				throw {
					errCode: ERROR.MESSAGE_NOT_FOUND
				}
			}
			
			return {
				success: true,
				message: this.t('message.delete_success')
			}
		} catch (error) {
			console.error('deleteMessage error:', error)
			throw error
		}
	},
	
	/**
	 * 批量删除消息
	 * @param {object} params 批量删除参数
	 * @param {Array} params.messageIds 消息ID列表
	 * @returns {object} 删除结果
	 */
	async batchDeleteMessages(params) {
		const { messageIds } = params
		
		if (!messageIds || !Array.isArray(messageIds) || messageIds.length === 0) {
			throw {
				errCode: ERROR.PARAM_REQUIRED,
				errMsgValue: { param: 'messageIds' }
			}
		}
		
		try {
			const userId = await getUserId(this)
			
			// 批量删除
			const deleteResult = await messageCollection.where({
				_id: dbCmd.in(messageIds),
				user_id: userId
			}).remove()
			
			return {
				success: true,
				message: this.t('message.batch_delete_success'),
				deleted: deleteResult.deleted
			}
		} catch (error) {
			console.error('batchDeleteMessages error:', error)
			throw error
		}
	},
	
	/**
	 * 发送系统消息
	 * @param {object} params 发送参数
	 * @param {string} params.userId 接收用户ID
	 * @param {string} params.type 消息类型
	 * @param {object} params.title 消息标题（多语言）
	 * @param {object} params.content 消息内容（多语言）
	 * @param {object} [params.data] 附加数据
	 * @param {number} [params.priority=1] 优先级
	 * @returns {object} 发送结果
	 */
	async sendSystemMessage(params) {
		const { userId, type, title, content, data, priority = 1 } = params
		
		if (!userId || !type || !content) {
			throw {
				errCode: ERROR.PARAM_REQUIRED,
				errMsgValue: { param: !userId ? 'userId' : (!type ? 'type' : 'content') }
			}
		}
		
		try {
			// 验证用户存在性（可选，根据业务需求）
			// await this._validateUser(userId)
			
			// 创建消息
			const messageData = {
				user_id: userId,
				type,
				title: title || { 'zh-Hans': '', 'en': '' },
				content,
				data: data || {},
				is_read: false,
				priority,
				create_time: new Date(),
				update_time: new Date()
			}
			
			const messageResult = await messageCollection.add(messageData)
			
			return {
				success: true,
				message: this.t('message.send_success'),
				messageId: messageResult.id
			}
		} catch (error) {
			console.error('sendSystemMessage error:', error)
			throw error
		}
	},
	
	/**
	 * 批量发送系统消息
	 * @param {object} params 批量发送参数
	 * @param {Array} params.userIds 接收用户ID列表
	 * @param {string} params.type 消息类型
	 * @param {object} params.title 消息标题（多语言）
	 * @param {object} params.content 消息内容（多语言）
	 * @param {object} [params.data] 附加数据
	 * @param {number} [params.priority=1] 优先级
	 * @returns {object} 批量发送结果
	 */
	async batchSendSystemMessage(params) {
		const { userIds, type, title, content, data, priority = 1 } = params
		
		if (!userIds || !Array.isArray(userIds) || userIds.length === 0 || !type || !content) {
			throw {
				errCode: ERROR.PARAM_REQUIRED,
				errMsgValue: { param: !userIds ? 'userIds' : (!type ? 'type' : 'content') }
			}
		}
		
		try {
			// 批量创建消息
			const messages = userIds.map(userId => ({
				user_id: userId,
				type,
				title: title || { 'zh-Hans': '', 'en': '' },
				content,
				data: data || {},
				is_read: false,
				priority,
				create_time: new Date(),
				update_time: new Date()
			}))
			
			const results = await this._batchCreateMessages(messages)
			
			return {
				success: true,
				message: this.t('message.batch_send_success'),
				sent_count: results.successCount,
				failed_count: results.failedCount,
				message_ids: results.messageIds
			}
		} catch (error) {
			console.error('batchSendSystemMessage error:', error)
			throw error
		}
	},
	
	/**
	 * 获取未读消息数量
	 * @returns {object} 未读数量
	 */
	async getUnreadCount() {
		try {
			const userId = await getUserId(this)
			
			const unreadResult = await messageCollection.where({
				user_id: userId,
				is_read: false
			}).count()
			
			return {
				unreadCount: unreadResult.total
			}
		} catch (error) {
			console.error('getUnreadCount error:', error)
			throw error
		}
	},
	
	/**
	 * 全部标记为已读
	 * @returns {object} 标记结果
	 */
	async markAllAsRead() {
		try {
			const userId = await getUserId(this)
			
			// 全部标记为已读
			const updateResult = await messageCollection.where({
				user_id: userId,
				is_read: false
			}).update({
				is_read: true,
				read_time: new Date(),
				update_time: new Date()
			})
			
			return {
				success: true,
				message: this.t('message.mark_all_read_success'),
				updated: updateResult.updated
			}
		} catch (error) {
			console.error('markAllAsRead error:', error)
			throw error
		}
	},
	
	/**
	 * 获取消息详情
	 * @param {object} params 查询参数
	 * @param {string} params.messageId 消息ID
	 * @returns {object} 消息详情
	 */
	async getMessageDetail(params) {
		const { messageId } = params
		
		if (!messageId) {
			throw {
				errCode: ERROR.PARAM_REQUIRED,
				errMsgValue: { param: 'messageId' }
			}
		}
		
		try {
			const userId = await getUserId(this)
			
			const messageResult = await messageCollection.where({
				_id: messageId,
				user_id: userId
			}).get()
			
			if (messageResult.data.length === 0) {
				throw {
					errCode: ERROR.MESSAGE_NOT_FOUND
				}
			}
			
			// 获取当前请求的语言
			const language = this.language || 'zh-Hans'
			
			// 转换数据格式
			const transformedData = transformMultiLangData(messageResult.data, language, {
				multiLangFields: ['title', 'content'],
				keepFields: [
					'message_id', 'user_id', 'type', 'is_read', 'priority',
					'data', 'read_time', 'create_time', 'update_time'
				],
				idMapping: { '_id': 'message_id' }
			})[0]
			
			// 如果消息未读，自动标记为已读
			if (!transformedData.is_read) {
				await messageCollection.doc(messageId).update({
					is_read: true,
					read_time: new Date(),
					update_time: new Date()
				})
				transformedData.is_read = true
				transformedData.read_time = new Date()
			}
			
			return {
				message: transformedData
			}
		} catch (error) {
			console.error('getMessageDetail error:', error)
			throw error
		}
	},
	
	/**
	 * 获取消息统计信息
	 * @param {object} params 查询参数
	 * @param {string} [params.type] 消息类型
	 * @returns {object} 统计信息
	 */
	async getMessageStats(params = {}) {
		const { type } = params
		
		try {
			const userId = await getUserId(this)
			
			let whereCondition = {
				user_id: userId
			}
			
			if (type) {
				whereCondition.type = type
			}
			
			// 获取各种统计数据
			const [totalResult, unreadResult, readResult] = await Promise.all([
				messageCollection.where(whereCondition).count(),
				messageCollection.where({ ...whereCondition, is_read: false }).count(),
				messageCollection.where({ ...whereCondition, is_read: true }).count()
			])
			
			return {
				total: totalResult.total,
				unread: unreadResult.total,
				read: readResult.total
			}
		} catch (error) {
			console.error('getMessageStats error:', error)
			throw error
		}
	},
	
	// ==================== 私有方法 ====================
	
	/**
	 * 批量创建消息
	 * @private
	 * @param {Array} messages 消息列表
	 * @returns {object} 创建结果
	 */
	async _batchCreateMessages(messages) {
		let successCount = 0
		let failedCount = 0
		const messageIds = []
		
		// 分批处理，避免单次操作过多数据
		const batchSize = 100
		for (let i = 0; i < messages.length; i += batchSize) {
			const batch = messages.slice(i, i + batchSize)
			
			try {
				const batchResults = await Promise.allSettled(
					batch.map(message => messageCollection.add(message))
				)
				
				batchResults.forEach(result => {
					if (result.status === 'fulfilled') {
						successCount++
						messageIds.push(result.value.id)
					} else {
						failedCount++
						console.error('批量创建消息失败:', result.reason)
					}
				})
			} catch (error) {
				console.error('批量创建消息批次失败:', error)
				failedCount += batch.length
			}
		}
		
		return {
			successCount,
			failedCount,
			messageIds
		}
	},
	
	/**
	 * 验证用户是否存在
	 * @private
	 * @param {string} userId 用户ID
	 */
	async _validateUser(userId) {
		// 这里可以添加用户验证逻辑
		// 例如检查用户是否存在、是否有效等
		// 具体实现根据业务需求来定
		return true
	}
}
